<template>
  <div>
    <div :class="{setButton:isActive}">
      <el-button type="primary" icon="el-icon-plus"  size="small" @click="goTeacherCourseHandle">老师课程分配</el-button>
      <el-button
        size="small"
        icon="el-icon-delete-solid"
        type="danger"
        @click="batchDelete"
      >批量删除</el-button>
      <el-button type="primary" icon="el-icon-aim" size="small" @click="getSerachData">搜索</el-button>
      <el-select v-model="value" filterable placeholder="查询类型" size="small" clearable class="setSelection">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>

      <el-input
        prefix-icon="el-icon-search"
        size="small"
        placeholder="请输入查询内容"
        v-model="input"
        :class="{setInput:isActive}"
        clearable
      ></el-input>

      <el-button
        class="setExcelButton"
        type="success"
        icon="el-icon-document"
        size="small"
        @click="exportData"
      >导出表格</el-button>
    </div>
    <el-table
      ref="filterTable"
      :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
      style="width: 100%"
      :default-sort="{prop:'course_teacher_Id',order:'descending'}"
      stripe
      @selection-change="selected"
      max-height="1000"
    >
      <el-table-column fixed type="selection" width="55"></el-table-column>
      <el-table-column fixed prop="userName" sortable label="用户账号" width="150"></el-table-column>
      <el-table-column fixed prop="nickName" sortable label="用户姓名" width="150"></el-table-column>
      <el-table-column fixed prop="courseName" sortable label="课程名称" width="150"></el-table-column>
      <el-table-column sortable v-if="false" prop="course_teacher_Id" label="老师课程ID" width="150"></el-table-column>
      <el-table-column sortable v-if="false" prop="course_Id" label="课程ID" width="150"></el-table-column>
      <el-table-column sortable v-if="false" prop="user_Id" label="用户ID" width="150"></el-table-column>
      <el-table-column prop="comment" label="备注" width="120"></el-table-column>
      <el-table-column prop="recordTime" :formatter="dateFormat" label="记录时间" sortable width="150"></el-table-column>
      <el-table-column prop="updateTime" :formatter="dateFormat" label="更新时间" sortable width="150"></el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(scope.row)"></el-button>

          <el-button type="danger" icon="el-icon-delete" size="mini" @click="open(scope.row)"></el-button>

          <el-button
          type="warning"
            @click.native.prevent="deleteRow(scope.$index, tableData)"
            icon="el-icon-remove-outline"
            size="mini"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page="currentPage"
        :page-sizes="[3,6,8,10,20,100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length"
      ></el-pagination>
    </div>

    <!-- 修改班级课程信息dialog -->
    <el-dialog title="班级课程信息" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="老师信息：" :label-width="formLabelWidth">
         <el-input
            v-model="form.userInfo"
            autocomplete="off"
            prefix-icon="el-icon-user-solid"
            :width="formLabelWidth"
            show-word-limit
            disabled="false"
            resize
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="课程信息：" :label-width="formLabelWidth">
          <el-select
        v-model="form.courseId"
        filterable
        placeholder="查询课程"
        size="small"
        clearable
        class="setDialogDateAndSex"
      >
        <el-option
          v-for="item in courseNameData"
          :key="item.courseId"
          :label="item.courseName"
          :value="item.courseId"
        ></el-option>
      </el-select>
        </el-form-item>
        <el-form-item label="信息备注：" :label-width="formLabelWidth">
          <el-input
            v-model="form.comment"
            autocomplete="off"
            prefix-icon="el-icon-s-comment"
            :width="formLabelWidth"
            maxlength="255"
            show-word-limit
            resize
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <template slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdate">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { export2Excel } from '../../common/js/util'
import inputExcel from '../common/inputExcel'
import moment from 'moment'
export default {
  inject: ['reload'],
  components: { inputExcel },
  data () {
    return {
      dialogFormVisible: false,
      addRoleFormVisible: false,
      formLabelWidth: '120px',
      pageSize: 6,
      currentPage: 1,
      tableData: [],
      selectedCheckBox: [],
      courseNameData: [], // 所有权限名称数据
      input: '',
      isActive: true,
      value: '',
      options: [
        {
          value: 'userName',
          label: '用户账号'
        },
        {
          value: 'nickName',
          label: '用户姓名'
        },
        {
          value: 'courseName',
          label: '课程名称'
        }
      ],
      columns: [
        { title: '学生班级ID', key: 'course_teacher_Id' },
        { title: '课程ID', key: 'course_Id' },
        { title: '班级ID', key: 'class_Id' },
        { title: '备注', key: 'comment' },
        { title: '创建时间', key: 'recordTime' },
        { title: '更新时间', key: 'updateTime' }
      ],
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称,不能为空', trigger: 'blur' }
        ]
      },
      form: {
        userInfo: '',
        courseTeacherId: '', // 老师课程ID
        userId: '', // 用户ID
        courseId: '', // 班级ID
        comment: '', // 备注
        recordTime: '', // 创建时间
        updateTime: '' // 更新时间
      }

    }
  },
  created () {
    this.initData()
    this.getAllCourseName()
  },
  methods: {
    goTeacherCourseHandle () {
      // 班级老师分配页面
      this.$router.replace('/teacherCourseAllocation')
    },
    dateFormat (row, column) {
      // 修改时间格式
      var date = row[column.property]

      if (date === undefined) {
        return ''
      } else if (date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    getSerachData () {
      if (this.input === '' && this.value !== '') {
        this.$confirm('查询内容不能为空！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } else if (this.value === '' && this.input !== '') {
        this.$confirm('查询类型内容不能空！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } else if (this.value === '' && this.input === '') {
        this.initData()
      } else {
        this.$axios
          .post('/courseTeachers/serachs', {
            json: this.value + ',' + this.input
          })
          .then(response => (this.tableData = response.data.data))
          .catch(function (error) {
            // 请求失败处理
            console.log(error)
          })
      }
    },
    exportData () {
      // Excel导出数据
      export2Excel(this.columns, this.tableData)
    },
    onSubmit (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleAdd()
          console.log('success submit!!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    selected: function (value) {
      // 复选框获取已经被选择的记录
      this.selectedCheckBox = value
    },
    batchDelete: function () {
      // 获取所有选中行的id组成的字符串，以逗号分隔
      var ids = this.selectedCheckBox.map(item => item.course_teacher_Id).join()

      console.log(ids)
      // 批量删除操作方法
      this.$confirm('此操作将批量删除已选择记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.handleDeleteUsersByIds(ids)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleDeleteUsersByIds: function (array) {
      // 删除操作方法
      // alert(index.userId);
      this.$axios
        .post('/courseTeachers/dels', {
          Ids: array
        })
        .then(response => {
          if (response.data.code === 200) {
            setTimeout(() => {
              this.reload()
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.initData()
            }, 300)
          } else {
            this.$message({
              message: '删除失败',
              type: 'error'
            })
          }
        })
        .catch(failResponse => {
          this.$message({
            message: '请求失败',
            type: 'warning'
          })
        })
    },
    handleSizeChange (val) {
      this.currentPage = 1
      this.pageSize = val
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange (val) {
      this.currentPage = val
      console.log(`当前页: ${val}`)
    },
    deleteRow (index, rows) {
      rows.splice(index, 1)
    },
    open (index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.handleDelete(index.course_teacher_Id)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleEdit: function (rows) {
      // 打开修改操作dialog方法
      this.dialogFormVisible = true // 打开dialog
      this.form.userInfo = rows.userName + '-' + rows.nickName
      this.form.courseTeacherId = rows.course_teacher_Id
      this.form.courseId = rows.course_Id
      this.form.userId = rows.user_Id
      this.form.comment = rows.comment
      this.form.recordTime = rows.recordTime
      this.form.updateTime = rows.updateTime
      console.log(rows)
    },
    handleUpdate: function () {
      // 执行更新操作方法
      this.dialogFormVisible = false
      if (this.form != null) {
        this.$axios
          .put('/courseTeachers', {
            json: this.form
          })
          .then(response => {
            if (response.data.code === 200) {
              setTimeout(() => {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })

                this.initData()
              }, 300)
            } else {
              this.$message({
                message: '修改失败',
                type: 'warning'
              })
            }
          })
          .catch(function (error) {
            // 请求失败处理
            console.log(error)
          })
      }
      // alert(this.form.toString);
    },
    handleDelete: function (index) {
      // 删除操作方法
      this.$axios
        .delete('/courseTeachers/' + index)
        .then(response => {
          if (response.data.code === 200) {
            setTimeout(() => {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.initData()
            }, 300)
          } else {
            this.$message({
              message: '删除失败',
              type: 'error'
            })
          }
        })
        .catch(failResponse => {
          this.$message({
            message: '请求失败',
            type: 'warning'
          })
        })
    },
    getAllCourseName () {
      // 获取所有角色名称
      this.$axios
        .get('/courseTeachers/courseNames')
        .then(response => {
          this.courseNameData = response.data.data
          console.log(response.data.data)
        })
        .catch(function (error) {
          // 请求失败处理
          console.log(error)
        })
    },
    initData () {
      // 初始化数据
      this.$axios
        .get('/courseTeachers/teacherAndCourses')
        .then(response => (this.tableData = response.data.data))
        .catch(function (error) {
          // 请求失败处理
          console.log(error)
        })
    }
  }
}
</script>
<style scoped>
.setInput {
  width: 200px;
}
.setButton {
  text-align: left;
  margin-left: 0%;
  height: 60px;
}
.setSelection {
  width: 100px;
  background-color: dodgerblue;
}
.setExcelButton {
  margin-left: 5%;
}
.setDialogDateAndSex {
  width: 470px;
}
</style>
